package StoreGUIs;

import Model.Store;
import Model.InternalDBManager;
import javax.persistence.*;
import javax.swing.ImageIcon;
import Supermarket.AppMessages;
import javax.swing.JDialog;

/**
 *
 * @author bagi
 */
public class EditStoreForm extends javax.swing.JDialog {
    
    private static EntityManager em;
    private Store store = new Store();
    private int selectedRow = 0;
    //μεταβλητή καθορισμού τροποποίησης (false) ή δημιουργίας νέου καταστήματος (true)
    private boolean statusFlag;
    private boolean statusUpdate = false;

    /**
     * Creates new form EditStoreFrom
     */
    public EditStoreForm(java.awt.Frame parent, boolean modal) {
        super(parent, modal);
        em = InternalDBManager.getEm();
        initComponents();
        this.setIconImage(new
                ImageIcon(getClass().getResource("..\\Images\\cart.png")).getImage()); 
        setAlwaysOnTop(true);
    }
    
    public EditStoreForm(java.awt.Frame parent, boolean modal, Store s, boolean st) {
        super(parent, modal);
        em = InternalDBManager.getEm();
        statusFlag = st;
        this.store = s;
        initComponents();
        this.setIconImage(new
                ImageIcon(getClass().getResource("..\\Images\\cart.png")).getImage()); 
        setAlwaysOnTop(true);
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {
        bindingGroup = new org.jdesktop.beansbinding.BindingGroup();

        storeInDB = store;
        StoreForm = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        StoreNameField = new javax.swing.JTextField();
        jLabel3 = new javax.swing.JLabel();
        StoreAddressField = new javax.swing.JTextField();
        ErrorMessageLabel = new javax.swing.JLabel();
        StoreNameMissingLabel = new javax.swing.JLabel();
        StoreAddressMissingLabel = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        StoreIdField = new javax.swing.JTextField();
        jLabel10 = new javax.swing.JLabel();
        RegisterButton = new javax.swing.JButton();
        CancelButton = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Διαχείριση Στοιχείων Καταστήματος");

        StoreForm.setBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.RAISED));

        jLabel1.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N
        jLabel1.setText("Κατάστημα:");

        StoreNameField.setColumns(30);
        StoreNameField.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N
        StoreNameField.setToolTipText("");
        StoreNameField.setCursor(new java.awt.Cursor(java.awt.Cursor.TEXT_CURSOR));

        org.jdesktop.beansbinding.Binding binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, storeInDB, org.jdesktop.beansbinding.ELProperty.create("${storeName}"), StoreNameField, org.jdesktop.beansbinding.BeanProperty.create("text"));
        bindingGroup.addBinding(binding);

        StoreNameField.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                StoreNameFieldActionPerformed(evt);
            }
        });

        jLabel3.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N
        jLabel3.setText("Διεύθυνση:");

        StoreAddressField.setColumns(50);
        StoreAddressField.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N

        binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, storeInDB, org.jdesktop.beansbinding.ELProperty.create("${address}"), StoreAddressField, org.jdesktop.beansbinding.BeanProperty.create("text"));
        bindingGroup.addBinding(binding);

        ErrorMessageLabel.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N
        ErrorMessageLabel.setForeground(new java.awt.Color(255, 0, 0));
        ErrorMessageLabel.setToolTipText("");

        StoreNameMissingLabel.setForeground(java.awt.Color.red);
        StoreNameMissingLabel.setText("    ");
        StoreNameMissingLabel.setToolTipText("");

        StoreAddressMissingLabel.setForeground(java.awt.Color.red);
        StoreAddressMissingLabel.setText("    ");
        StoreAddressMissingLabel.setToolTipText("");

        jLabel2.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N
        jLabel2.setText("Κωδικός:");
        jLabel2.setToolTipText("");

        StoreIdField.setEditable(false);
        StoreIdField.setBackground(new java.awt.Color(204, 204, 204));
        StoreIdField.setBorder(javax.swing.BorderFactory.createEtchedBorder());
        StoreIdField.setEnabled(false);

        binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, storeInDB, org.jdesktop.beansbinding.ELProperty.create("${storeId}"), StoreIdField, org.jdesktop.beansbinding.BeanProperty.create("text"));
        bindingGroup.addBinding(binding);

        javax.swing.GroupLayout StoreFormLayout = new javax.swing.GroupLayout(StoreForm);
        StoreForm.setLayout(StoreFormLayout);
        StoreFormLayout.setHorizontalGroup(
            StoreFormLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(StoreFormLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(StoreFormLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(ErrorMessageLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 399, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGroup(StoreFormLayout.createSequentialGroup()
                        .addGroup(StoreFormLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                            .addComponent(jLabel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(jLabel1, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(jLabel2, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(StoreFormLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(StoreFormLayout.createSequentialGroup()
                                .addComponent(StoreNameField, javax.swing.GroupLayout.PREFERRED_SIZE, 251, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(StoreNameMissingLabel))
                            .addComponent(StoreIdField, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, StoreFormLayout.createSequentialGroup()
                                .addComponent(StoreAddressField, javax.swing.GroupLayout.PREFERRED_SIZE, 308, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(StoreAddressMissingLabel)))))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        StoreFormLayout.setVerticalGroup(
            StoreFormLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(StoreFormLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(StoreFormLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(StoreIdField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(7, 7, 7)
                .addGroup(StoreFormLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(StoreNameField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(StoreNameMissingLabel)
                    .addComponent(jLabel1))
                .addGap(7, 7, 7)
                .addGroup(StoreFormLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel3)
                    .addComponent(StoreAddressField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(StoreAddressMissingLabel))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(ErrorMessageLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 23, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        jLabel2.getAccessibleContext().setAccessibleName("Κωδικός: ");

        jLabel10.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Images/supermarket_320.png"))); // NOI18N

        RegisterButton.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N
        RegisterButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Images/save_16.png"))); // NOI18N
        RegisterButton.setText("Καταχώρηση");
        RegisterButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                RegisterButtonActionPerformed(evt);
            }
        });

        CancelButton.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N
        CancelButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Images/cancel_16.png"))); // NOI18N
        CancelButton.setText("Ακύρωση");
        CancelButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                CancelButtonActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(StoreForm, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(8, 8, 8)
                        .addComponent(jLabel10, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(RegisterButton, javax.swing.GroupLayout.DEFAULT_SIZE, 125, Short.MAX_VALUE)
                            .addComponent(CancelButton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(StoreForm, javax.swing.GroupLayout.PREFERRED_SIZE, 131, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(RegisterButton, javax.swing.GroupLayout.PREFERRED_SIZE, 33, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(CancelButton, javax.swing.GroupLayout.PREFERRED_SIZE, 33, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addComponent(jLabel10))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        bindingGroup.bind();

        pack();
        setLocationRelativeTo(null);
    }// </editor-fold>//GEN-END:initComponents

    private void RegisterButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_RegisterButtonActionPerformed
        //Σβήνουμε τυχόν μηνύματα λάθους (labels)
        initLabels();
        //αν η μεταφορά και αποθήκευση έγινε κανονικά κλείσιμο της φόρμας
        statusUpdate = DataManager();
        if(statusUpdate){
            this.setVisible(false);
        }
    }//GEN-LAST:event_RegisterButtonActionPerformed

    private void CancelButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_CancelButtonActionPerformed

        this.statusUpdate = false;
        this.setVisible(false);
    }//GEN-LAST:event_CancelButtonActionPerformed

    private void StoreNameFieldActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_StoreNameFieldActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_StoreNameFieldActionPerformed

    //μέθοδος που αναλαμβάνει να αποθηκεύσει τα δεδομένα της φόρμας
    public boolean DataManager(){
        boolean success = false;
        boolean StoreDataInCorrectForm = registerStore();
        
        //αν τα δεδομένα του καταστήματος είναι στη σωστή μορφή 
        if (StoreDataInCorrectForm){
            //αν πρόκειται για εισαγωγή νέου καταστήματος
            if(statusFlag){
                //και το κατάστημα δεν υπάρχει στη ΒΔ
                if (!isStoreInDB()){
                    if (UpdateStoreToDB())
                        success = true;
                //αν το κατάστημα υπάρχει στη ΒΔ
                }else{
                    AppMessages.DataExistsMessage(this); 
                }
            } else{ 
                //αν πρόκειται για τροποποίηση καταστήματος (statusLabel=false)
                //ζητείται επιβεβαίωση των αλλαγών πριν την ενημέρωση της ΒΔ (statusLabel=false)
                int confirmChoice = AppMessages.ConfirmationMessage(this);
                if (confirmChoice == 0 ){
                    if (UpdateStoreToDB())
                        success = true;
                }
            }
        }
        return success;
    }
    
    //έλεγχος και μεταφορά των πεδίων της φόρμας σε αντικείμενο store
    //για την καταχώρηση στη βάση.
    public boolean registerStore(){
        boolean success = true;
        //Έλεγχος εισαγωγής ονόματος καταστήματος
        if(StoreNameField.getText().isEmpty()){
            ErrorMessageLabel.setText(AppMessages.FieldsMissingMsg);
            StoreNameMissingLabel.setText("(*)");
            success = false;
        }else{
            store.setStoreName(StoreNameField.getText());   
        }
        //Έλεγχος εισαγωγής διεύθυνσης καταστήματος
        if(StoreAddressField.getText().isEmpty()){
           ErrorMessageLabel.setText(AppMessages.FieldsMissingMsg);
           StoreAddressMissingLabel.setText("(*)");
           success = false;
        }else{
            store.setAddress(StoreAddressField.getText());   
        }
        //επίστρεψε το αποτέλεσμα της μεταφοράς δεδομένων
        return success;
    }
    
    //Πρόσθήκη-Τροποποίηση στοιχείων καταστήματος στη ΒΔ
    private boolean UpdateStoreToDB() {
        try {
             if (!em.getTransaction().isActive()){
                em.getTransaction().begin();
            }
            if (statusFlag)
               em.persist(store);   //εάν νέο κατάστημα
            else em.merge(store);   //εάν τροποποίηση υφιστάμενου
            em.getTransaction().commit();
            //Εμφανίζει μήνυμα επιτυχίας 
            AppMessages.SuccessMessage(this);
            //em.close();
            return true;
        } catch (SecurityException e) {
            AppMessages.FailureMessage(this,e);
            em.getTransaction().rollback();
            return false;
        }
    }
    
    //μέθοδος που αρχικοποιεί όλα τα labels που χρησιμοποιούνται
    //για την εμφάνιση μηνυμάτων
    private void initLabels() {
        ErrorMessageLabel.setText("");
        StoreNameMissingLabel.setText("");
        StoreAddressMissingLabel.setText("");
    }

    //boolean μέθοδος που ελέγχει αν το κατάστημα υπάρχει στη ΒΔ
    private boolean isStoreInDB(){
        boolean success = false;
        try{
            if (!em.getTransaction().isActive()){
                    em.getTransaction().begin();
            }  
            //ψάχνει το κατάστημα με το όνομά του
            Store s_exists = (Store)em.createNamedQuery("Store.findByStoreName")
                .setParameter("storeName", store.getStoreName()).getSingleResult();   
            //αν βρεθεί επιστρέφει true
            success = true;
        }catch(NoResultException e){
            //αν δε βρεθεί επιστρέφει false
            success = false;
        }
        return success;
    } 
   
       /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(EditStoreForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the dialog */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                EditStoreForm dialog = new EditStoreForm(new javax.swing.JFrame(), true);
                dialog.addWindowListener(new java.awt.event.WindowAdapter() {
                    @Override
                    public void windowClosing(java.awt.event.WindowEvent e) {
                        System.exit(0);
                    }
                });
                dialog.setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton CancelButton;
    private javax.swing.JLabel ErrorMessageLabel;
    private javax.swing.JButton RegisterButton;
    private javax.swing.JTextField StoreAddressField;
    private javax.swing.JLabel StoreAddressMissingLabel;
    private javax.swing.JPanel StoreForm;
    private javax.swing.JTextField StoreIdField;
    private javax.swing.JTextField StoreNameField;
    private javax.swing.JLabel StoreNameMissingLabel;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel10;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private Model.Store storeInDB;
    private org.jdesktop.beansbinding.BindingGroup bindingGroup;
    // End of variables declaration//GEN-END:variables

  //επιστρέφει το αποτέλεσμα της ενημέρωσης
  public boolean getStatusUpdate(){
      return this.statusUpdate;
  }  
  
  //επιστρέφει το κατάστημα που τροποιήθηκε
  public Store getStore(){
      return this.store;
  }
}
